package com.buddies.lottery.ui.login;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MotionEventCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.buddies.lottery.BuildConfig;
import com.buddies.lottery.R;
import com.buddies.lottery.base.BaseActivity;
import com.buddies.lottery.data.bean.User;
import com.buddies.lottery.ui.MainActivity;
import com.buddies.lottery.ui.register.RegisterActivity;
import com.buddies.lottery.utils.AppExitUtils;

public class LoginActivity extends BaseActivity<LoginContract.Presenter> implements LoginContract.View, View.OnClickListener {

    private static final int REQUEST_CODE_REGISTER = 1;

    private TextView mForgetPwdTV;
    private Button mLoginBTN;
    private EditText mPhoneET;
    private EditText mPwdET;
    private ImageView mClearPhoneIV;
    private ImageView mClearPwdIV;

    private int iconClickTimes;
    private long iconStartClickTime;
    private long iconLastClickTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setBackgroundDrawableResource(R.color.transparent);

        mPresenter = new LoginPresenter(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        mLoginBTN = (Button)findViewById(R.id.btn_login);
        mForgetPwdTV = (TextView)findViewById(R.id.btn_forget_pwd);
        mPhoneET = (EditText)findViewById(R.id.et_phone);
        mPwdET = (EditText)findViewById(R.id.et_pwd);
        mClearPhoneIV = (ImageView)findViewById(R.id.iv_clear);
        mClearPwdIV = (ImageView)findViewById(R.id.iv_clear_pwd);

        mLoginBTN.setOnClickListener(this);
        mForgetPwdTV.setOnClickListener(this);
        mClearPhoneIV.setOnClickListener(this);
        mClearPwdIV.setOnClickListener(this);

        findViewById(R.id.tv_code_login).setOnClickListener(this);
    }

    @Override
    protected void initData() {
        setTitle(getResources().getString(R.string.login));

        findViewById(R.id.tv_title).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                long curTime = System.currentTimeMillis();
                if (event.getPointerCount() >= 2 && MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_POINTER_UP) {
                    iconClickTimes++;
                    if (iconClickTimes == 1) {
                        iconStartClickTime = curTime;
                    }
                    if (curTime - iconLastClickTime > 500 || curTime - iconStartClickTime > 5000) {
                        iconClickTimes = 0;
                    }
                    if (iconClickTimes >= 3) {
                        iconClickTimes = 0;
//                        UrlConstants.doChangeEnv();
                    }
                    iconLastClickTime = curTime;
                }
                return true;
            }
        });

        mPhoneET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                mClearPhoneIV.setVisibility(editable.length() == 0 ? View.GONE : View.VISIBLE);
                setCommitBtnEnable();
            }
        });
        mPhoneET.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                mClearPhoneIV.setVisibility(mPhoneET.length() == 0 || !hasFocus ? View.GONE : View.VISIBLE);
            }
        });

        mPwdET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                mClearPwdIV.setVisibility(editable.length() == 0 ? View.GONE : View.VISIBLE);
                setCommitBtnEnable();
            }
        });
        mPwdET.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                mClearPwdIV.setVisibility(mPwdET.length() == 0 || !hasFocus ? View.GONE : View.VISIBLE);
            }
        });

        if (BuildConfig.DEBUG) {
            mPhoneET.setText("luohong722");
            mPwdET.setText("123456");
        }

        setCommitBtnEnable();
    }

    public void setCommitBtnEnable() {
        boolean enabled = mPhoneET.length() > 0 && mPwdET.length() > 0;
        mLoginBTN.setEnabled(enabled);
        if (!enabled) {
            mLoginBTN.setAlpha(0.3f); //TextColor(getResources().getColor(R.color.black_30_percent_transparent));
        } else {
            mLoginBTN.setAlpha(1.0f); //TextColor(getResources().getColor(R.color.black));
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_login:
                if (checkPhone() && checkPwd()) {
                    requestLogin();
                }
                KeyboardUtils.hideSoftInput(getActivity());
                break;

            case R.id.btn_forget_pwd:
//                toRegister("forgetPwd");
                ToastUtils.showShort("暂不支持找回密码，请注册新号后联系客服！");
                break;

            case R.id.iv_clear:
                mPhoneET.setText("");
                break;

            case R.id.iv_clear_pwd:
                mPwdET.setText("");
                break;

            case R.id.tv_code_login:
                toRegister(null);
                break;

            default:
                break;
        }
    }

    private void toRegister(String from) {
        Intent intent = new Intent();
        intent.setClass(this, RegisterActivity.class);
        intent.putExtra("phone", getPhone());
        intent.putExtra("from", from);
        startActivityForResult(intent, REQUEST_CODE_REGISTER);
        finish();
    }

    private void requestLogin() {
        final String phone = getPhone();
        final String pwd = getPwd();
        mPresenter.postLogin(phone, EncryptUtils.encryptMD5ToString(pwd));
        showProgressDialog(R.string.login_processing);
    }

    @Override
    public void onLoginSuccess(User user) {
        showToast(R.string.login_success);

        if (isTaskRoot()) {
            MainActivity.launch(getActivity());
        }

        setResult(RESULT_OK);
        finish();
    }

    private boolean checkPhone() {
        String phone = getPhone();

        boolean check = false;
        if (TextUtils.isEmpty(phone)) {
            showToast(getResources().getString(R.string.login_phone_number_require));
        } else if (phone.contains(" ")) {
            showToast(getResources().getString(R.string.login_phone_number_not_blank));
        } else if (phone.length() < 6 || phone.length() > 18) {
            showToast(getResources().getString(R.string.login_phone_number_length_not_right));
        } else {
            check = true;
        }

        return check;
    }

    public String getPhone() {
        return mPhoneET.getText().toString();
    }

    private boolean checkPwd() {
        String pwd = getPwd();

        boolean check = false;
        if (TextUtils.isEmpty(pwd)) {
            showToast(getResources().getString(R.string.login_password_require));
        } else if (pwd.length() < 6 || pwd.length() > 20) {
            showToast(getResources().getString(R.string.login_password_condition));
        } else {
            check = true;
        }

        return check;
    }

    public String getPwd() {
        return mPwdET.getText().toString();
    }

    @Override
    public void onBackPressed() {
        AppExitUtils.getInstance().onBackPressed(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_REGISTER && resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        }
    }

    public static void launch(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

}
